package com.guxiuwei.sys.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guxiuwei.sys.common.Result;
import com.guxiuwei.sys.entity.Eroom;
import com.guxiuwei.sys.entity.User;
import com.guxiuwei.sys.mapper.EroomMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 谷秀伟
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/sys/eroom")
public class EroomController {
    @Autowired
    private EroomMapper eroomMapper;

    //获取前端传入的默认显示页码，页面容量数，
    // 和搜索框查询条件，对数据库中机房巡检信息表进行分页查询
    @GetMapping("/selectAll")
    public Result<?> findPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "16") Integer pageSize,
            @RequestParam(defaultValue = "") String search,
            @RequestParam(defaultValue = "") String searchdate){
        System.out.println(searchdate);

        LambdaQueryWrapper<Eroom> wrapper = Wrappers.<Eroom>lambdaQuery();
        if (StrUtil.isNotBlank(search) || StrUtil.isNotBlank(searchdate)){
            wrapper.like(Eroom::getRid,search);
            wrapper.like(Eroom::getPatroldate,searchdate);
        }
        Page<Eroom> eroomPage = eroomMapper.selectPage(new Page<>(pageNum, pageSize),wrapper );
        System.out.println(eroomPage);
        return Result.success(eroomPage);
    }

    //权限（现场组） 添加机房巡检记录
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('现场组')")
    public Result<?> save(@RequestBody Eroom eroom){
        Eroom res = eroomMapper.selectOne(Wrappers.<Eroom>lambdaQuery()
                .eq(Eroom::getRid, eroom.getRid())
                .eq(Eroom::getPatroldate, eroom.getPatroldate()));
        if (res != null){
            return Result.error("0","该巡检记录已存在");
        } else {
            eroomMapper.insert(eroom);
            return Result.success();
        }
    }

    //权限（现场组） 对前端传入的eroom对象进行修改更新操作
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('现场组')")
    public Result<?> update(@RequestBody Eroom eroom){
        eroomMapper.updateById(eroom);
        return Result.success();
    }

    //权限（现场组） 对前端传入的eroom对象的uid进行相关记录删除操作
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('现场组')")
    public Result<?> delete(@PathVariable Long id){
        eroomMapper.deleteById(id);
        return Result.success();
    }



}

